/**
 * 补助单详情
 * @author hongwei 2018-09-28
 */
(function (window) {
    'use strict';
    var allowanceInfo = function (params) {
        $.extend(this.params, params);
        this._init();
    };

    allowanceInfo.prototype = {
        //参数
        params : {
            // flag : true
            // ,reason : ''
            // ,status : 0
            sign_url : ''
            ,sing_flag : false
        }

        //初始化
        ,_init : function () {
            var that = this;

            that.getAllowanceInfo();//step01:获取新增出差申请单数据
            that.signatureOn();     //step02:签名操作
            that.showOrder();       //step03:显示订单
        }

        //step01:获取新增出差申请单数据
        ,getAllowanceInfo : function () {
            var that = this;

            var allowance_id = $api.getStorage('allowance_id');
            var param = {};
            param.url = Config.travel.allowanceInfo;
            param.data = {
                id: allowance_id
            };
            //请求申请单列表接口*/
            ajax(param, function(ret) {
                if (ret.code === 1) {

                    //step1:审批轨迹
                    var interText = doT.template($("#approve_tpl").text());
                    $("#approve_info").append(interText(ret.data));

                    //step2:订单信息
                    $("#book_user_name").text(ret.data.book_user.user_name);
                    $("#request_code").text(ret.data.request_code);
                    $("#create_time").text(ret.data.create_time);
                    $("#travel_start_time").text(ret.data.travel_start_time);
                    $("#travel_end_time").text(ret.data.travel_end_time);
                    $("#travel_allowance").text(ret.data.travel_allowance);
                    $("#economy_sum").text(ret.data.economy_sum);
                    $("#total_money").text(ret.data.total_money);

                    //4.1 报销单信息录入 - 基本信息
                    var interText2 = doT.template($("#detail_tpl").text());
                    $("#allowance_detail").after(interText2(ret.data));

                    //4.2 报销单信息录入 - 酒店
                    var interText3 = doT.template($("#allowance_tpl").text());
                    $("#allowance_detail").after(interText3(ret.data));

                    //step2详情和step5金额合计:申请单关联订单
                    if (ret.data.order_list.plane.total > 0 || ret.data.order_list.hotel.total > 0 || ret.data.order_list.train.total > 0) {
                        var interText = doT.template($("#order_tpl").text());
                        //车票
                        if (ret.data.order_list.train.total > 0) {
                            $("#order_list").after(interText(ret.data.order_list.train.data));
                            var priceTrain = 0;
                            for (var i = 0; i < ret.data.order_list.train.data.length; i++) {
                                priceTrain += parseFloat(ret.data.order_list.train.data[i].order_total_price);
                            }
                            var trainHtml = '';
                            trainHtml += '<div class="aui-info aui-margin-t-10 aui-padded-l-10 aui-padded-r-10" style="border-bottom: 1px solid #dddddd;margin:0;background:white;">';
                            trainHtml += '<div class="aui-info-item"><span class="aui-margin-l-5">火车票订单</span></div>';
                            trainHtml += '<div class="aui-info-item"><span class="aui-margin-r-10" style="color:orange;">';
                            trainHtml += '合计：' +priceTrain + '元;' ;
                            trainHtml += '</span><span class="aui-margin-r-5 show_order" data-group="train" >展开</span></div></div>';
                            $("#order_list").after(trainHtml);
                        }
                        //酒店
                        if (ret.data.order_list.hotel.total > 0) {
                            $("#order_list").after(interText(ret.data.order_list.hotel.data));
                            var priceHotel = 0;
                            for (var i = 0; i < ret.data.order_list.hotel.data.length; i++) {
                                priceHotel += parseFloat(ret.data.order_list.hotel.data[i].order_total_price);
                            }
                            var hotelHtml = '';
                            hotelHtml += '<div class="aui-info aui-margin-t-10 aui-padded-l-10 aui-padded-r-10" style="border-bottom: 1px solid #dddddd;margin:0;background:white;">';
                            hotelHtml += '<div class="aui-info-item"><span class="aui-margin-l-5">酒店订单</span></div>';
                            hotelHtml += '<div class="aui-info-item"><span class="aui-margin-r-10" style="color:orange;">';
                            hotelHtml += '合计：' + priceHotel + '元';
                            hotelHtml += '</span><span class="aui-margin-r-5 show_order" data-group="hotel">展开</span></div></div>';
                            $("#order_list").after(hotelHtml);
                        }
                        //机票
                        if (ret.data.order_list.plane.total > 0) {
                            $("#order_list").after(interText(ret.data.order_list.plane.data));
                            var pricePlane = 0;
                            for (var i = 0; i < ret.data.order_list.plane.data.length; i++) {
                                pricePlane += parseFloat(ret.data.order_list.plane.data[i].order_total_price);
                            }
                            var planeHtml = '';
                            planeHtml += '<div class="aui-info aui-margin-t-10 aui-padded-l-10 aui-padded-r-10" style="border-bottom: 1px solid #dddddd;margin:0;background:white;">';
                            planeHtml += '<div class="aui-info-item"><span class="aui-margin-l-5">机票订单</span></div>';
                            planeHtml += '<div class="aui-info-item"><span class="aui-margin-r-10" style="color:orange;">';
                            planeHtml += '合计：' + pricePlane + '元';
                            planeHtml += '</span><span class="aui-margin-r-5 show_order" data-group="plane">展开</span></div></div>';
                            $("#order_list").after(planeHtml);
                        }
                    }

                    //step6:审批签字
                    var interText = doT.template($("#approve_sign").text());
                    $("#sign_info").append(interText(ret.data));

                    //step7:7.审核按钮等
                    var interText2 = doT.template($("#approve_option_tpl").text());
                    $("#approve_option").append(interText2(ret.data));

                    that.initImg();//step12:点击图片放大
                    that.initApproveButton();    //step13:初始化显示“通过审核”和“驳回申请”按钮
                } else {
                    $toast(ret.msg);
                }
            })
        }

        //step02:签名操作
        ,signatureOn : function () {
            var that = this;

            $('.js-signature').on('jq.signature.changed', function() {
                var sing_flag = true;
                //合并参数
                var sing_flagTemp = {
                    sing_flag : sing_flag
                };
                $.extend(that.params, sing_flagTemp);
            });

        }

        //step03:显示订单
        ,showOrder :function () {
            $('body').on('click', '.show_order', function() {
                //折叠
                $('.order_' + $(this).attr('data-group')).toggle();
                //文字显示
                var i = $(this).text();
                if (i === '展开') {
                    $(this).empty().text('收回');
                } else if(i === '收回'){
                    $(this).empty().text('展开');
                }
            });
        }

        //step11:更改状态“审核/驳回”
        ,changeStatus : function () {
            var allowance_id = $api.getStorage('allowance_id');
            var param = {};
            param.url = Config.travel.allowanceExamineApprove;
            if (status == 1) {
                param.data = {
                    allowance_id: allowance_id,
                    approved_status: status,
                    dismissal_cause: reason
                };
            } else {
                param.data = {
                    allowance_id: allowance_id,
                    approved_status: status,
                    sign_url: sign_url
                };
            }
            ajax(param, function(ret) {
                if (ret.code === 1) {
                    $alert('成功', function() {
                        screenRotate();
                        setTimeout(function(){
                            location.reload();
                        },500);
                    });
                } else {
                    screenRotate();
                    $toast('审批失败');
                }
            })
        }

        //step12:点击图片放大
        , initImg : function () {
            $("img").on("click", function() {
                var url = $(this).attr("src");
                var html = '';
                html += '<div class="wang-enlarge-plugin-div">';
                html += '<div class="wang-enlarge-cover-div"></div>';
                html += '<div class="wang-enlarge-img-div"><img src="' + url + '"></div>';
                html += '</div>';
                $("body").append(html)
            });
            $(document).on("click", ".wang-enlarge-plugin-div", function() {
                this.remove()
            });
        }

        //step13:初始化显示“通过审核”和“驳回申请”按钮
        ,initApproveButton : function () {
            var that = this;

            var flag = true;
            var reason = '';

            $(".changeStatus").click(function () {
                var status = $(this).find("input").val();
                if (!flag) {
                    return false;
                }
                flag = false;
                if(status === 1){
                    layer.open({
                        type: 1,
                        title: '选择驳回原因',
                        area: ['300px', '260px'], //宽高
                        content: $("#rejectCause"),
                        btn : '确定',
                        closeBtn : 1,
                        shadeClose : true,
                        yes : function () {
                            reason = $("#rejectCause input:checked").val();
                            changeStatus();
                            layer.closeAll();
                        }
                    });
                    flag = true;
                }else{
                    $('.js-signature').jqSignature();
                    api.setScreenOrientation({
                        orientation: 'landscape_left'
                    });
                    $('html').addClass('noscroll');
                    layer.open({
                        type: 1,
                        title: '签名审核',
                        area: [api.frameHeight + 'px', '300px'], //宽高
                        offset : ['10px','25px'],//坐标
                        content: $("#signPass"),
                        btn: ['清空', '确定'],
                        closeBtn: 1,
                        yes: function() {
                            that.clearCanvas();
                            return false;
                        },
                        btn2: function() {
                            if (!sing_flag) {
                                $toast("请签名");
                                return false;
                            }
                            that.saveSignature();
                            layer.closeAll();
                            return false;
                        },cancel: function(index, layero){
                            screenRotate();
                            flag = true;
                            layer.close(index)
                            return false;
                        }
                    });
                    flag = true;
                }
            });
        }

        //step14:清空画布
        ,clearCanvas : function () {
            $('.js-signature').jqSignature('clearCanvas');
            //sing_flag = false;
        }

        //step15:保存签名
        ,saveSignature : function (status) {
            var that = this;

            var sign_url = '';
            $('#signature').empty();
            var canvas = document.getElementsByTagName('canvas');
            var dataUrl = that.canvasToImage(canvas[0], "white");
            var param = {};
            param.url = Config.travel.uploadImgOss;
            param.data = {
                imgData: dataUrl
            };
            ajax(param, function(ret) {
                if (ret.code === 1) {
                    sign_url = ret.data;
                    //合并参数
                    var signUrlTemp = {
                        sign_url : sign_url
                    };
                    $.extend(that.params, signUrlTemp);

                    that.changeStatus(status);     //审核通过操作
                } else {
                    $toast(ret.msg);
                }
            })
        }

        //step16:画布转图片
        , canvasToImage : function (canvas, backgroundColor) {
            //cache height and width
            var w = canvas.width;
            var h = canvas.height;
            var data;

            var context = canvas.getContext('2d');
            if (backgroundColor) {
                //get the current ImageData for the canvas.
                data = context.getImageData(0, 0, w, h);

                //store the current globalCompositeOperation
                var compositeOperation = context.globalCompositeOperation;

                //set to draw behind current content
                context.globalCompositeOperation = "destination-over";

                //set background color
                context.fillStyle = backgroundColor;

                //draw background / rect on entire canvas
                context.fillRect(0, 0, w, h);
            }

            //get the image data from the canvas
            var imageData = canvas.toDataURL("image/png");

            if (backgroundColor) {
                //clear the canvas
                context.clearRect(0, 0, w, h);

                //restore it with original / cached ImageData
                context.putImageData(data, 0, 0);

                //reset the globalCompositeOperation to what it was
                context.globalCompositeOperation = compositeOperation;
            }

            //return the Base64 encoded data url string
            return imageData;
        }

    };

    window.allowanceInfo = allowanceInfo;
})(window);